package com.tool4j.util.velocity;

import com.tool4j.common.EnvEnum;
import com.tool4j.util.SpringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.ExtendedProperties;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.apache.velocity.runtime.resource.Resource;
import org.apache.velocity.runtime.resource.loader.ResourceLoader;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class VelocityTemplateLoader extends ResourceLoader {

    Map<String, Long> fileLastModified = new HashMap<>();

    /**
     * 获取模板文件根路径
     *
     * @return
     */
    public static String getRootPath() {
        switch (EnvEnum.getValueByKey(SpringUtil.getEnv())) {
            case DEV:
                return "D:\\my-code\\tool4j-ai\\tool4j-ai-server\\src\\main\\resources\\template\\code-template";
            case PROD:
            default:
                return "/app/template/code-template";
        }
    }

    @Override
    public void init(ExtendedProperties configuration) {
    }

    @Override
    public InputStream getResourceStream(String source) throws ResourceNotFoundException {
        File file = null;
        try {
            file = getResourceFile(source);
            return new FileInputStream(file);
        } catch (Exception e) {
            return this.getClass().getResourceAsStream(source);
        } finally {
            if (file != null)
                fileLastModified.put(source, file.lastModified());
        }
    }

    @Override
    public boolean isSourceModified(Resource resource) {
        return true;
    }

    @Override
    public long getLastModified(Resource resource) {
        return 0;
    }

    private File getResourceFile(String name) {
        return new File(String.format("%s/%s", getRootPath(), name));
    }
}